<?php
/**
 * Author: Hancock
 * Email: 84622365@qq.com
 * Date: 3/23/2016
 * Des: 测试控制器
 */
defined('INHkMvc') or exit('Access Invalid!');

class AppController extends Controller
{
    /**
    * 根据密钥获取账户ID
    * @return [type] [description]
    */
    protected function getMemberIdByToken()
    {
        $token =$this->_postParam('token','');
        self::is_error_parameters($token, 'token');
        if ($_SESSION['member_id']) {
            $db_token = M('app.member')->getOneByMemberId($_SESSION['member_id'], 'token')['token'];
            if ($token == $db_token) {
                return $_SESSION['member_id'];
            } else {
                self::apiReturn($token, '登录密钥错误', 298);
            }
        } else {
            $res = M('app.member')->getOneByToken($token, 'member_id');
            if ($res) {
                if ($res['member_id']) {
                    $member_id = intval($res['member_id']);
                    $_SESSION['member_id'] = $member_id;
                    return $member_id;
                } else {
                    self::apiReturn($res, '数据出错啦', 299);
                }
            } else {
                self::apiReturn($token, '登录密钥错误', 298);
            }
        }
    }
    /**
     * 获取验证码
     */
    public function getRegisterCodeAct()
    {
        $mobile = trim($this->_postParam('mobile',''));
        if (!preg_match("/^1[34578]\d{9}$/", $mobile)) {
            ajaxReturn(0, "手机格式有错", 0);
        }
        $code = createncode(6);
        $_SESSION['verification_code'] = $code;
        $_SESSION['mobile'] =$mobile;
        if(M('app.member')->getMemberByMobile($mobile,'member_id')){
            ajaxReturn(0, "该号码已注册", 1);  
        }
        $res = smsSend($mobile,['code'=>$code], 'default_code');
        if ($res['status'] == 1) {
            ajaxReturn(1, "验证码已发送", 1);
        } else {
            ajaxReturn(0, "验证码发送失败", 0);
        }
    }

    public function getVerificationCodeAct()
    {
        $mobile = trim($this->_postParam('mobile',''));
        if (!preg_match("/^1[34578]\d{9}$/", $mobile)) {
            ajaxReturn(0, "手机号码格式有错", 0);
        }
        $code = createncode(6);
        $_SESSION['verification_code'] = $code;
        $_SESSION['mobile'] =$mobile;
        if(!M('app.member')->getMemberByMobile($mobile,'member_id')){
            ajaxReturn(0, "该号码未注册 请先注册", 1);  
        }
        $res = smsSend($mobile,['code'=>$code], 'default_code');
        if ($res['status'] == 1) {
            ajaxReturn(1, "验证码已发送", 1);
        } else {
            ajaxReturn(0, "验证码发送失败", 0);
        }
    }
    /**
    * 注册页
    */
    public function registerAct()
    {   
        $mobile=trim($this->_postParam('mobile',''));
        if (!preg_match("/^1[34578]\d{9}$/", $mobile)) {
            ajaxReturn(0, "手机号码格式有错", 0);
        }
        $pwd=trim($this->_postParam('pwd',''));
        $code = trim($this->_postParam('verification_code',''));
        if(empty($mobile) || empty($pwd) || empty($code)){
           ajaxReturn(0,'用户名或密码不为空',0);
        }
        if($mobile!=$_SESSION['mobile']){
            ajaxReturn(0,'号码出错',0);
        }
        $where = [];
        $where[]=['mobile'=>$mobile];
        $mod=M('app.member');
        if (!$mod->getMemberByMobile($mobile,'member_id')) {
            if ($_SESSION['verification_code'] == $code) {
                $mod->begin();
                $res = $mod->register($mobile,'',$pwd);
                if ($res===false) {
                    $mod->rollback();
                    ajaxReturn(0, "注册失败", 0);
                } else {
                    $member = $mod->getMemberInfo($mobile);
                    $res=M('app.member_vip')->applyExperienceVip($member['member_id']);
                    if($res===false || $res==false){
                        $mod->rollback();
                        ajaxReturn(0, "注册失败", 0);
                    }else{
                        $_SESSION['member_id'] = $member['member_id'];
                        $_SESSION['type'] = 0;
                        $_SESSION['logo'] = $member['head_img'];
                        $_SESSION['nickname'] = $member['nick_name'];
                        $customer = M('app.customer')->find($where);
                        if (!empty($customer)) {
                            M('app.customer')->update(['is_reg' => 1, 'update_time' => time()], $where);
                        }
                        $member['mobile']=$member['mobile']?$member['mobile']:$mobile;
                        $mod->commit();
                        ajaxReturn($member, "注册成功", 1);
                    } 
                }
            } else {
                ajaxReturn(0, "验证码错误", 0);
            }
        } else {
            ajaxReturn(0, "该号码已注册", 0);
        }
    }

    /**
    * 登录
    */
    public function loginAct()
    {
        $mobile=trim($this->_postParam('mobile',''));
        if (!preg_match("/^1[34578]\d{9}$/", $mobile)) {
            ajaxReturn(0, "手机号码格式有错", 0);
        }
        $password=trim($this->_postParam('password',''));
        if(empty($mobile) || empty($password)){
           ajaxReturn(0,'用户名或密码不为空',0);
        }
        $where = [];
        $where[]=['mobile'=>$mobile];
        $member = M("app.member")->appLogin($mobile, $password);
        if ($member == false || $member===false) {
            $error = 1;
            $status = 0;
            $content = "登录失败";
            $data = M('app.member')->getMemberLoginLog($where, $content, $error, $status);
            $data['type'] = 3;
            M('app.member_login_log')->addLog($data);
            ajaxReturn(0, "用户名或密码错误", 0);
        } else {
            session_destroy();
            $error = 0;
            $status = 1;
            $content = "登录成功";
            $_SESSION['member_id'] = $member['member_id'];
            $_SESSION['logo'] = $member['head_img'];
            $_SESSION['nickname'] = $member['nick_name'];
            $_SESSION['type'] = intval($_POST['type']);
            $data = M('app.member')->getMemberLoginLog($where, $content, $error, $status);
            $data['type'] = 3;
            M('app.member_login_log')->addLog($data);
            $vip_status = M('app.member_vip')->getMemberVipStatusByMemberId($member['member_id'],'status')['status'];
            $_SESSION['status'] =intval($vip_status);
            $customer = M('app.customer')->find($where);
            if ($customer['id'] > 0) {
                M('app.customer')->update(['member_id' => $member['member_id'], 'is_reg' => 1, 'update_time' => time()], $where);
            }
            $member['mobile']=$member['mobile']?$member['mobile']:$mobile;
            ajaxReturn($member, "登录成功", 1);
        }
    }
    //***************个人设置***************
    /**
    * 编辑支付宝账号
    */
    public function editAliAccountAct()
    {
        $member_id = self::getMemberIdByToken();
        if ($_SESSION['verification_code'] == $this->_postParam('verification_code','')) {
                $data=[];
                $data['ali_account'] = trim($this->_postParam('payment_account',''));
                $data['name'] = trim($this->_postParam('payment_name',''));
                if(empty($data['ali_account']) || empty($data['name'])){
                     ajaxReturn(0,'支付宝账号或真实姓名不为空',0);
                }
                $member_vip = M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'id');
                if (!empty($member_vip)) {
                    $res = M('app.member_vip')->update($data, ['member_id' => $member_id]);
                } else {
                    $data['member_id'] = $member_id;
                    $data['status'] = 0;
                    $res = M('app.member_vip')->insert($data);
                }
                if ($res===false) {
                    ajaxReturn(0, '编辑失败', 0);
                } else {
                    ajaxReturn(1, '编辑成功', 1);
                }
        } else {
            ajaxReturn(0, '验证码错误', 0);
        }
    }

    /**
    * 修改头像
    */
    public function editAvatarAct()
    {   
        $member_id = self::getMemberIdByToken();
        if ($_POST['file']) {
            $file_path = ROOT_PATH . "data/member/avatar/";
            $file_name = md52('member' . $member_id . time()) . ".jpg";
            $headimgurl = str_replace(ROOT_PATH, ROOT_URL, $file_path . $file_name);
            include_once(ROOT_PATH . 'inc/upload.class.php');
            $file = @new upload();
            $res_up = $file->uploadInputImage($_POST['file'], $file_name, $file_path);
            if ($res_up) {
                include_once ROOT_PATH . 'inc/oss.class.php';
                $oss = new oss();
                $up = @$oss->uploadFile($file_path . $file_name);
                if ($up['status'] != true) {
                    ajaxReturn("failed", $up['msg'], 0);
                }
                $res = M("app.member")->update(['headimgurl' => $headimgurl], ['member_id' => $member_id]);
                if ($res) {
                    ajaxReturn($headimgurl, '上传修改成功', 1);
                } else {
                    unlink($file_path . $file_name);
                    ajaxReturn(0, '上传失败', 0);
                }
            } else {
                ajaxReturn(0, '上传失败', 0);
            }
        } else {
            ajaxReturn(0, '文件资源错误', 0);
        }
    }

    /**
    * 修改密码  短信修改
    */
    public function editPwdAct()
    {   
        $mobile=trim($this->_postParam('mobile',''));
        if (!preg_match("/^1[34578]\d{9}$/", $mobile)) {
            ajaxReturn(0, "手机号码格式有错", 0);
        }
        $new_password=trim($this->_postParam('new_password',''));
        if(empty($mobile) || empty($new_password)){
           ajaxReturn(0,'用户名或密码不为空',0);
        }
        if($mobile!=$_SESSION['mobile']){
            ajaxReturn(0,'号码出错',0);
        }
        if ($_SESSION['verification_code'] == trim($this->_postParam('verification_code',''))) {
            $res = M('app.member')->update(['password' => md52($new_password)], ['mobile' =>$mobile]);
            if ($res === false) {
                ajaxReturn(0, '修改失败', 0);
            } else {
                ajaxReturn(1, '修改成功', 1);
            }
        } else {
            ajaxReturn(0, '验证码出错', 0);
        }
    }

    /**
    * 修改密码 旧密码修改
    */
    public function editpasswordAct()
    {
        $member_id = self::getMemberIdByToken();
        $new_password=trim($this->_postParam('new_password',''));
        $old_password=trim($this->_postParam('old_password',''));
        if(empty($old_password) || empty($new_password)){
           ajaxReturn(0,'密码不为空',0);
        }
        $password = M('app.member')->getOneByMemberId($member_id,'password')['password'];
        if ($password == md52($old_password)) {
            $res = M('app.member')->update(['password' => md52($new_password)], ['member_id' => $member_id]);
            if ($res === false) {
                ajaxReturn(0, '修改失败', 0);
            } else {
                ajaxReturn(1, '修改成功', 1);
            }
        } else {
            ajaxReturn(0, '旧密码错误', 0);
        }
    }
    /**
    * 修改昵称
    */
    public function editNickNameAct()
    {
        $member_id = self::getMemberIdByToken();
        $nick_name=trim($this->_postParam('nick_name',''));
        if(empty($nick_name)){
           ajaxReturn(0,'昵称不为空',0);
        }
        $res = M('app.member')->update(['nickname'=>$nick_name], ['member_id' => $member_id]);
        if ($res===false) {
            ajaxReturn(0, '修改失败', 0);
        } else {
            ajaxReturn(1, '修改成功', 1);
        }
    }
    /**
    * 修改绑定手机
    */
    public function editBindMobileAct()
    {
        $member_id = self::getMemberIdByToken();
        $mobile=trim($this->_postParam('new_tel',''));
        if (!preg_match("/^1[34578]\d{9}$/", $mobile)) {
            ajaxReturn(0, "手机号码格式有错", 0);
        }
        if ($_SESSION['verification_code'] ==$this->_postParam('verification_code','')) {
            $res = M('app.member_vip')->update(['mobile'=>$mobile], ['member_id' => $member_id]);
            if ($res === false) {
                ajaxReturn(0, '修改失败', 0);
            } else {
                ajaxReturn(1, '修改成功', 1);
            }
        } else {
            ajaxReturn(0, '验证码出错啦！！！', 0);
        }
    }

    /**
    * 开通Vip
    */
    public function applyExperienceVipAct()
    {
        // $member_id = self::getMemberIdByToken();
        // $vip_status =M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'status')['status'];
        // if (intval($vip_status)!=0) {
        //     ajaxReturn(0, '用户已申请', 0);
        // } else {
        //     if (!empty($_POST['invite_code']) && array_key_exists('invite_code', $_POST)) {
        //         $member = M('app.member_invite_code')->field('member_id')->find(['code' => trim($_POST['invite_code'])]);
        //         if (!empty($member)) {
        //             $res = M('app.member_vip')->applyExperienceVip($_POST, $member_id);
        //             if ($res==false || $res===false) {
        //                 ajaxReturn(0, '邀请码错误', 0);
        //             } else {
        //                 ajaxReturn(1, '申请成功', 1);
        //             }
        //         } else {
        //             ajaxReturn(0, '邀请码失效', 0);
        //         }
        //     } else {
        //         ajaxReturn(0, '请填写邀请码', 0);
        //     }
        // }
    }
    /**
    * 申请提现
    */
    public function applyCashAct()
    {
        $member_id = self::getMemberIdByToken();
        if ($this->_postParam('member_integration_id','')== 0) {
            $member_integration_id = 0;
        } else {
            $member_integration_id = $this->_postParam('member_integration_id','');
        }
        $member_vip = M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'ali_account,status,mobile');
        if (!empty($member_vip)) {
            if ($_SESSION['verification_code'] ==$this->_postParam('verification_code','')) {
                $data = M('app.member_vip')->applyMemberAccount($this->_postParam('draw_money',''), $member_id, $member_vip['ali_account'], $member_vip['mobile'], $member_integration_id);
                if ($data === false || $data == false) {
                    ajaxReturn(0, '申请失败', 0);
                } else {
                    $params = ['running_no' => $data['running_no']];
                    //smsSend('15396019188',$params, 'balance_apply');
                    smsSend('18650320032', $params, 'balance_apply');
                    smsSend('15396019188', $params, 'balance_apply');
                    ajaxReturn($data, '申请成功', 1);
                }
            } else {
                ajaxReturn(0, '验证码错误', 0);
            }
        } else {
            ajaxReturn(0, '请先绑定账户', 0);
        }
    }

    /**
    * 获取会员信息
    */
    public function getMemberInfoAct()
    {
        $member_id = self::getMemberIdByToken();
        $member = M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'level,status');
        if (empty($member)) {
            $is_write = 0;
        } else {
            $is_write = 1;
        }
        $level = M('app.member_vip')->getMemberVip($member_id);
        if (isset($level['confirm_time']) && $level['confirm_time'] != NULL) {
            $start_time = date('Y-m-d', $level['confirm_time']);
            $end_time = date('Y-m-d', $level['confirm_time'] + ceil(($level['month'] / 12) * 365) * 86400);
        }
        $data = M('app.member_vip_level')->getMemberVipLevelInfo();
        $data = array('data' => $data, 'level' => intval($member['level']), 'status' => intval($member['status']), 'end_time' => $end_time, 'start_time' => $start_time, 'is_write' => $is_write);
        ajaxReturn($data, '获取成功', 1);
    }
    /**
     * 获取支付宝信息
     */
    public function getAliAccountAct()
    {
        $member_id = self::getMemberIdByToken();
        $data = M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'ali_account,name username');
        if ($data === false) {
            ajaxReturn(0, '获取失败', 0);
        } else {
            ajaxReturn($data, '获取成功', 1);
        }
    }
    /**
    * 获取订单
    */
    public function getOrderAct()
    {
        $member_id = self::getMemberIdByToken();
        $level=M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'level')['level'];
        $fee=M('app.member_vip_level')->getMemberLevelFee($level);
        if(!empty($_POST['order_time'])){
            $time=strtotime($_POST['order_time']);
        }else{
            $time=time();
        }
        $date=explode('-', date('Y-m-d',$time));
        $start_time=strtotime($date[0] . '-' .$date[1]. '-01');
        $end_time=strtotime($date[0] . '-' . ($date[1]+1) . '-01');
        $data=[];
        $balance=M('app.member_order')->getMemberIntegrationByAddTime($member_id,2,$start_time,$end_time)*$fee;
        $unbalance=M('app.member_order')->getMemberIntegrationByAddTime($member_id,1,$start_time,$end_time)*$fee;
        $rights_income=M('app.rights_member_order')->countSums('rights_tb_est_income',$member_id,$start_time,$end_time);
        $total_income=M('app.rights_member_order')->countSums('rights_total_income',$member_id,$start_time,$end_time);
        $data['balance']=$balance-$total_income;
        $data['unbalance']=$unbalance-($rights_income-$total_income);
        if (intval($_POST['order_type']) == 0) {
            $status = 4;
            $data['order'] = M('app.member_order')->getMemberOrderListByTime($member_id,$start_time,$end_time,$status,$fee);
        } else if (intval($_POST['order_type']) == 1) {
            $status = 1;
            $data['order']= M('app.member_order')->getMemberOrderListByTime($member_id,$start_time,$end_time,$status,$fee);
        } else if (intval($_POST['order_type']) == 2) {
            $status = 2;
            $data['order'] = M('app.member_order')->getMemberOrderListByTime($member_id,$start_time,$end_time,$status,$fee);
        } else if (intval($_POST['order_type']) == 3) {
            $status = 0;
            $data['order']= M('app.member_order')->getMemberOrderListByTime($member_id,$start_time,$end_time,$status,$fee);
        }else if(intval($_POST['order_type'])==4){
            $data['order'] = M('app.rights_member_order')->getRightsOrderByMemberIdByTime($member_id,$start_time,$end_time);
        }
        if ($data === false) {
            ajaxReturn(0, '数据异常', 0);
        } else {
            ajaxReturn($data, '获取成功', 1);
        }
    }
    /**
     * 获取24月订单数量
     */
    public function getTwoYearMemberOrderAct(){
        $member_id =self::getMemberIdByToken();
        $time=time();
        $date=explode('-', date('Y-m-d',$time));
        $day=$date[0]-2;
        $data=[];
        for ($i=1; $i <=24 ; $i++) { 
            if($date[1]+$i>12){
               if($date[1]+$i>24){
                $start_time=strtotime(($day+2) . '-' .($date[1]+$i-24). '-01');
               }else{
                $start_time=strtotime(($day+1) . '-' .($date[1]+$i-12). '-01');
               }
            }else{
               $start_time=strtotime($day . '-' .($date[1]+$i). '-01'); 
            }
            if($date[1]+$i+1>12){
               if($date[1]+$i+1>24){
                $end_time=strtotime(($day+2) . '-' .($date[1]+$i-23). '-01');
               }else{
                $end_time=strtotime(($day+1) . '-' .($date[1]+$i-11). '-01');
               }
            }else{
               $end_time=strtotime($day . '-' .($date[1]+$i+1). '-01'); 
            }
            $data[24-$i]['time']=$start_time;
            $data[24-$i]['date']=date('Y-m-d',$start_time);
            $data[24-$i]['num']=count(M('app.member_order')->getMemberOrderCountByTime($member_id,$start_time,$end_time));
        }
        ajaxReturn($data,'获取成功',1); 
    }
    /**
    * 获取邀请码
    */
    // public function getInviteCode_action()
    // {
    //     $member_id = self::getMemberIdByToken();
    //     $code = M('app.member_invite_code')->field('id,code,status')->select(['invite_member_id' => $member_id]);
    //     if (!empty($code)) {
    //         ajaxReturn($code, '获取成功', 1);
    //     } else {
    //         $code = M('app.member_invite_code')->getInviteCodeByMemberId($member_id);
    //         if ($code === false) {
    //             ajaxReturn(0, '请求出错', 0);
    //         } else {
    //             ajaxReturn($code, '获取成功', 1);
    //         }
    //     }
    // }

    /**
    * 获取提现明细
    */
    public function getCashListAct()
    {
        $member_id = self::getMemberIdByToken();
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $page_size = isset($_POST['page_size']) ? intval($_POST['page_size']) : 10;
        $data = M('app.member_balance_apply')->getLogListByMemberId($member_id, '', '', $page, $page_size);
        $count = M('app.member_balance_apply')->count(['member_id' => $member_id]);
        $res = array('count' => $count, 'list' => $data);
        if ($data === false) {
            ajaxReturn(0, '非法获取', 0);
        } else {
            ajaxReturn($res, '获取成功', 1);
        }
    }

    /**
     * 新版获取个人中心
     */
    public function getNewMemberCenterAct(){
        $member_id =self::getMemberIdByToken();
        $level=M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'level')['level'];
        $fee=M('app.member_vip_level')->getMemberLevelFee($level);
        $data=[];
        $member = M('app.member_vip')->getMemberVipAccount($member_id);
        $member['total'] = $member['total'] - $member['rights_total_income'];
        $member['est_income'] = $member['est_income'] - $member['rights_tb_est_income'];
        if($member['unbalance']==$member['est_income']-$member_id['total']){
            $data['unbalance']=$member['unbalance'];
        }else{
            $data['unbalance']=$member['est_income']-$member_id['total'];
            M('app.member_vip')->update(['unbalance'=>$member['est_income']-$member_id['total']],['member_id'=>$member_id]);
        }
        $data['balance']=$member['balance'];
        $data['est_income']=$member['est_income'];
        $data['order']=M('app.member_order')->getMemberOrderList($member_id,1,5);
        if(!empty($data['order'])){
            foreach ($data['order'] as $key => $value) {
                $data['order'][$key]['est_income']=$value['est_income']*$fee;      
            } 
        }
        ajaxReturn($data,'获取成功',1);
    }

    // /**
    // * 添加收藏 删除收藏
    // */
    // public function editGoodCollect_action()
    // {
    //     $member_id = self::getMemberIdByToken();
    //     if (intval($_POST['good_id']) == 0) {
    //         ajaxReturn(0, '数据异常', 0);
    //     }
    //     $data = M('app.good_collect')->find(['member_id' => $member_id, 'entity_id' => intval($_POST['good_id'])]);
    //     if (!empty($data)) {
    //         $res = M('app.good_collect')->allocationDeleteGroup($member_id, intval($_POST['good_id']));
    //     } else {
    //         $res = M('app.good_collect')->insert(['member_id' => $member_id, 'entity_id' => intval($_POST['good_id']), 'add_time' => time()]);
    //     }
    //     if ($res === false) {
    //         ajaxReturn(0, '操作失败', 0);
    //     } else {
    //         ajaxReturn(1, '操作成功', 1);
    //     }
    // }
    
    /**
    * 获取新版本信息
    * @return [type] [description]
    */
    public function getVersionAct()
    {
        $currentVersion = $_POST['currentVersion'];
        $mod = M('app.app_version');
        $android = $mod->getCurrentVersion($currentVersion, 0, 'force,info,url,version');
        $ios = $mod->getCurrentVersion($currentVersion, 1, 'force,info,url,version');
        $data = [
            'android' => $android,
            'ios' => $ios,
        ];
        if ($data === false) {
            ajaxReturn(0, '获取不到', 0);
        } else {
            ajaxReturn($data, '获取到了', 1);
        }
    }
    /**
    * 获取规则
    */
    public function getMemberRulesAct()
    {
        $member_id = self::getMemberIdByToken();
        $data = [];
        $data['score'] = M('app.member_rules')->getMemberRulesByType(0);
        $data['score_info'] = M('app.member_rules')->getMemberRulesByType(1);
        ajaxReturn($data, '获取成功', 1);
    }

    /**
    * 获取管家
    */
    public function getOneCustomerServiceAct(){
        $member_id = self::getMemberIdByToken();
        $data = M('app.customer_service')->getCustomerServiceByUids(16);
        if($data===false){
            ajaxReturn(0,'获取失败',0);
        }else{
            ajaxReturn($data,'获取成功',1);
        }
    }
    /**
    * 获取淘口令
    */
    public function getShareTpwdAct()
    {
        $member_id = self::getMemberIdByToken();
        $good_id = intval($this->_postParam('good_id',''));
        if ($good_id == 0) {
            ajaxReturn(0, '非法请求', 0);
        }
        $member = M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'status,ad_zone_id');
        if (intval($member['status']) != 1) {
            $member_id = 1;
        }
        $mod=M('app.good');
        $mod->begin();
        $good = $mod->field('pict_url,title')->find(['id' => $good_id]);
        if(empty($good)){
            ajaxReturn(0,'获取失败',0);
        }
        $shareTpwd=$mod->getMemberGoodTbPassForExcel($member_id,$good_id,$good['pict_url'],$good['title']);
        if(!empty($shareTpwd)){
            $mod->commit();
            ajaxReturn($shareTpwd,'获取成功',1);
        }else{
            $mod->rollback();
            ajaxReturn(0,'获取繁忙 稍后再试...',0);
        }
    }
    /**
     * 长链接转化成短链接
     */
    public function getSpreadClickUrlByUrlAct()
    {    
        $member_id = self::getMemberIdByToken();
        $good_id = intval($this->_postParam('good_id',''));
        if ($good_id == 0) {
            ajaxReturn(0, '非法请求', 0);
        }
        $status = M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'status')['status'];
        if (intval($status) != 1) {
            $member_id = 1;
        }
        $mod = M('app.good');
        $mod->begin();
        $data = $mod->getMemberGoodClickUrlForExcel($member_id, $good_id);
        if (!empty($data)) {
            $mod->commit();
            ajaxReturn($data['click_url'], '获取成功', 1);
        } else {
            $mod->rollback();
            ajaxReturn(0, '获取失败', 0);
        }
    }
    /**
    * 购物车整合
    */
    public function shoppingCartAct(){
        $member_id = self::getMemberIdByToken();
        $level = M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'level')['level'];
        $fee=M('app.member_vip_level')->getMemberLevelFee($level);
        $add_good=$_POST['add_good'];
        $delete_good=$_POST['delete_good'];
        $mod=M('app.shop_cart');
        $mod->begin();
        if(!empty($delete_good)){
            foreach ($delete_good as $k => $v) {
                $res=$mod->delete(['member_id'=>$member_id,'good_id'=>$v['good_id'],'good_type'=>$v['good_type']]);
                if($res===false){
                    $mod->rollback();
                    ajaxReturn(0,'删除失败',0);
                }  
            }
        }
        if(!empty($add_good)){
            foreach ($add_good as $key => $value) {
                if(!$mod->find(['good_id'=>$value['good_id'],'member_id'=>$member_id,'good_type'=>$value['good_type']])){
                    $res=$mod->insert(['member_id'=>$member_id,'good_id'=>$value['good_id'],'good_type'=>$value['good_type'],'add_time'=>time(),'update_time'=>time()]); 
                    if($res===false){
                        $mod->rollback();
                        ajaxReturn(0,'添加失败',0);
                    }   
                }   
            }
        }
        $good=[];
        $fields=[
                    'good.id',
                    'good.pict_url',
                    'good.title',
                    'good.item_url',
                    'good.user_type',
                    'good.define_title',
                    'good.zk_final_price',
                    'good.tk_rate',
                    'good.shop_rate',
                    'good.define_tk_rate',
                    'good.define_pict_url',
                    'good.seller_id',

            ];    
        $goodList=$mod->field('good_id,good_type')->order('id desc')->select(['member_id'=>$member_id]);
        if(!empty($goodList)){
            foreach ($goodList as $ky => $ve) {
                if($ve['good_type']==1){
                    $tb_good=M('app.good')->field($fields)->find(['id'=>$ve['good_id']]);
                    if ($tb_good['define_tk_rate']>0) {
                        $good[$ky]['tk_rate'] = $tb_good['define_tk_rate']*$fee;
                    }else if($tb_good['shop_rate']>0){
                        $good[$ky]['tk_rate'] = $tb_good['shop_rate']*$fee;
                    }else{
                        $good[$ky]['tk_rate']=$tb_good['tk_rate']*$fee;  
                    }
                    $tb_good['title']=$tb_good['define_title']?$tb_good['define_title']:$tb_good['title'];
                    $tb_good['pict_url']=$tb_good['define_pict_url']?$tb_good['define_pict_url']:$tb_good['pict_url'];
                    $good[$ky]['good_id']=$tb_good['id'];
                    $good[$ky]['user_type']=$tb_good['user_type'];
                    $good[$ky]['pict_url']=$tb_good['pict_url']; 
                    $good[$ky]['title']=$tb_good['title']; 
                    $good[$ky]['good_type']=1;  
                    $good[$ky]['zk_final_price']=$tb_good['zk_final_price'];
                    if(!empty($tb_good['seller_id'])){
                        $seller=M('app.admin_seller')->field('tb_seller_name,logo,tb_shop_name')->find(['tb_seller_id'=>$tb_good['seller_id']]);
                        $good[$ky]['seller_name']=$seller['tb_shop_name']?$seller['tb_shop_name']:$seller['tb_seller_name'];
                        $good[$ky]['logo']=$seller['logo'];
                    } else{
                        $good[$ky]['seller_name']='';
                        $good[$ky]['logo']='';
                    }  
                    $good[$ky]['share_url']='';
                    $good[$ky]['is_soldout']=1;
                    if(empty($good[$ky]['share_url'])){
                        $good[$ky]['is_soldout']=0;
                    }
                }else{
                    $owner_good=M('app.owner_good')->field('good_name,pict_url,good_price,source,id')->find(['id'=>$ve['good_id']]);
                    $good[$ky]['tk_rate']=0;
                    $good[$ky]['title']=$owner_good['good_name'];
                    $good[$ky]['pict_url']=$owner_good['pict_url'];
                    $good[$ky]['good_id']=$owner_good['id'];
                    $good[$ky]['user_type']=0;
                    $good[$ky]['zk_final_price']=$owner_good['good_price'];
                    $good[$ky]['seller_name']='';
                    $good[$ky]['logo']='';
                    $good[$ky]['good_type']=0;
                    $good[$ky]['share_url']=$owner_good['source'];
                    $good[$ky]['is_soldout']=0; 
                }
            }
        }
        $mod->commit();
        ajaxReturn($good,'获取成功',1);
    }
    /**
    * 根据黏贴板获取产品
    */
    public function getShopGoodByTbkPasswordAct()
    {   
        $member_id = self::getMemberIdByToken();
        $level = M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'level')['level'];
        $fee=M('app.member_vip_level')->getMemberLevelFee($level);
        $tbk_password=trim($_POST['tbk_password']);
        if(empty($tbk_password)){
            ajaxReturn(0, '非法请求', 0);
        }
        if (preg_match('/￥.*￥/i', $tbk_password,$match)) {
            $tbk_pass = $match[0];
        }else{
            $tbk_pass='';
        }
        $url = getNumiidByTbkPass($tbk_password);
        if(empty($url)){
            ajaxReturn(0, '', 0); 
        }
        $tb_url=$url;
        if(preg_match("/(&|\?)(id|item_id)=?[0-9]+/",$url,$iid)){
            $ids=explode('=', $iid[0]);    
        }else{
            $html = file_get_contents($url);
            $html = mb_convert_encoding($html, 'utf-8', 'GBK');
            if(preg_match("/(&|\?)(id|itemId)=?[0-9]+/",$html,$iid)){
                $ids=explode('=', $iid[0]);    
            }else{
                ajaxReturn(0, '', 0);
            }
        }
        $num_iid=$ids[1];
        if (!empty($num_iid)) {
            $data = [];
            $good_id = M('app.good')->field('id')->find(['num_iid' => $num_iid,'status'=>1,'is_delete'=>0])['id'];
            if (intval($good_id) <= 0) {
                $goods = getGoodsUrlForCapp($num_iid);
                if (!empty($goods['data']['pageList']) && isset($goods['data']['pageList'])) {
                    $good = $goods['data']['pageList'];
                    $tbk_info = [];
                    $tbk_info['seller_id'] = $good[0]['sellerId'];
                    $tbk_info['nick'] = $good[0]['nick'];
                    $tbk_info['user_type'] = $good[0]['userType'];
                    $tbk_info['zk_final_price'] = $good[0]['zkPrice'];
                    $tbk_info['num_iid'] = $good[0]['auctionId'];
                    $tbk_info['title'] = $good[0]['title'];
                    $tbk_info['pict_url'] = (strstr($good[0]['pictUrl'], "http:")) ? $good[0]['pictUrl'] : "http:" . $good[0]['pictUrl'];
                    $tbk_info['item_url'] = $good[0]['auctionUrl'];
                    $tbk_info['reserve_price'] = $good[0]['reservePrice'];
                    $tbk_info['tk_rate'] = $good[0]['tkRate'];
                    $tbk_info['add_time'] = time();
                    $tbk_info['is_update'] = 1;
                    $tbk_info['good_type'] = 2;
                    $tbk_info['status'] = 1;
                    $tbk_info['shop_name'] = $good[0]['shopTitle'];
                    M('app.good')->update(['shop_name' => $tbk_info['shop_name']], ['seller_id' => $tbk_info['seller_id']]);
                    $good_id = M('app.good')->addPlansGood($tbk_info);
                    if ($good_id == false) {
                        ajaxReturn(0, '商品不存在', 0);
                    }else{
                        $tbk_info['tk_rate']=$tbk_info['tk_rate']*$fee;
                        $tbk_info['good_id']=$good_id;
                        $tbk_info['good_type']=1;
                        if(!empty($tbk_info['seller_id'])){
                            $seller=M('app.admin_seller')->field('tb_seller_name,logo,tb_shop_name,shop_rate')->find(['tb_seller_id'=>$tbk_info['seller_id']]);
                            $tbk_info['seller_name']=$seller['tb_shop_name']?$seller['tb_shop_name']:$seller['tb_seller_name'];
                            $tbk_info['logo']=$seller['logo'];
                            if ($seller['shop_rate']>0) {
                                $tbk_info['tk_rate'] = $data['shop_rate']*$fee;
                            }
                        } else{
                            $tbk_info['seller_name']='';
                            $tbk_info['logo']='';
                        }
                            //$data_url=Models('Good')->getMemberGoodClickUrlForExcel($member_id,$good_id);
                        $tbk_info['share_url']='';
                        $tbk_info['is_soldout']=1;
                        if(empty($tbk_info['share_url'])){
                            $tbk_info['is_soldout']=0;
                        }
                        ajaxReturn($tbk_info, '获取成功', 1);
                    }
                }else{
                        $goods=getOwnerGood($num_iid);
                        if(!empty($goods)){
                            $data['good_name']=$goods['title'];
                            if (preg_match('/.*\.(jpg|jpeg|png)(_.*\.(jpg|jpeg|png))/', $goods['thumb'][0],$image)) {
                                $data['pict_url']=str_replace($image[2],'',$goods['thumb'][0]);
                            }else{
                                $data['pict_url']=$goods['thumb'][0]; 
                            }
                            $data['good_price']=$goods['price'];
                            $data['good_type'] = 0;
                            $data['source'] =$tb_url;
                            $owner_id = M('app.owner_good')->uploadOwnerGood($data, $member_id);
                            $data['good_id'] = $owner_id;
                            if ($owner_id === false || $owner_id == false) {
                                ajaxReturn(0, '获取出错', 0);
                            }
                            $datas=$data;
                            $datas['title']=$data['good_name'];
                            $datas['tk_rate'] = 0;
                            $datas['tbk_password'] =$tbk_pass;
                            $datas['good_url']=$tb_url;
                            $datas['share_url']=$tb_url;
                            $datas['is_soldout']=0;
                            $datas['zk_final_price']=$data['good_price'];
                            $datas['seller_name']='';
                            $datas['logo']='';
                            ajaxReturn($datas,'获取到商品信息',1);
                        }else{
                            ajaxReturn(0,'查无商品信息',0);
                        }
                } 
            }else{
                $data=M('app.good')->field('id,pict_url,title,user_type,define_title,zk_final_price,tk_rate,shop_rate,define_tk_rate,define_pict_url,seller_id')->find(['id'=>$good_id]);
                if ($data['define_tk_rate']>0) {
                    $data['tk_rate'] = $data['define_tk_rate']*$fee;
                }else if($data['shop_rate']>0){
                    $data['tk_rate'] = $data['shop_rate']*$fee;
                }else{
                    $data['tk_rate'] = $data['tk_rate']*$fee;
                }
                $data['title']=$data['define_title']?$data['define_title']:$data['title'];
                $data['pict_url']=$data['define_pict_url']?$data['define_pict_url']:$data['pict_url'];
                $data['good_id']=$data['id']; 
                $data['zk_final_price']=$data['zk_final_price'];
                $data['good_type']=1;
                if(!empty($data['seller_id'])){
                    $seller=M('app.admin_seller')->field('tb_seller_name,logo,tb_shop_name')->find(['tb_seller_id'=>$data['seller_id']]);
                    $data['seller_name']=$seller['tb_shop_name']?$seller['tb_shop_name']:$seller['tb_seller_name'];
                    $data['logo']=$seller['logo'];
                } else{
                    $data['seller_name']='';
                    $data['logo']='';
                }
                //$data_url=Models('Good')->getMemberGoodClickUrlForExcel($member_id,$good_id);
                $data['share_url']='';
                $data['is_soldout']=1;
                if(empty($data['share_url'])){
                    $data['is_soldout']=0;
                }  
                ajaxReturn($data,'获取成功',1);
            }
        } else {
            ajaxReturn(0, '获取繁忙 稍后再试', 0);
        }
    }
    /**
    * 新手教程
    */
    public function memberFqaAct(){
        $this->sign('title', 'Faq');
        $data = M('app.vr_fqa')->order('sort asc')->select(['is_delete'=>0]);
        include_once ROOT_PATH.'vr_crm/View/template/default/memberFqa.php';
    } 
    /**
     * 搜索标题
     */
    public function searchGoodByTitleAct(){
        $member_id = self::getMemberIdByToken();
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $page_size = isset($_POST['page_size']) ? intval($_POST['page_size']) : 40;
        $title = trim($this->_postParam('title',''));
        $level = M('app.member_vip')->getMemberVipStatusByMemberId($member_id,'level')['level'];
        $fee=M('app.member_vip_level')->getMemberLevelFee($level);
        if (empty($title)) {
           ajaxReturn([], '', 0);
        }
        $data = getGoodByTitle($title,$shopTag='yxjh',$page=1,$page_size=40);
        if(empty($data['data']['pageList'])){
            ajaxReturn([],'无相关商品',1);
        }
        $good = $data['data']['pageList'];
        $tbk_info = [];
        foreach ($good as $k => $v) {   
            $tbk_info[$k]['seller_id'] = $v['sellerId'];
            $tbk_info[$k]['nick'] = $v['nick'];
            $tbk_info[$k]['user_type'] = $v['userType'];
            $tbk_info[$k]['zk_final_price'] = $v['zkPrice'];
            $tbk_info[$k]['num_iid'] = $v['auctionId'];
            $tbk_info[$k]['title'] = $v['title'];
            $tbk_info[$k]['pict_url'] = (strstr($v['pictUrl'], "http:")) ? $v['pictUrl'] : "http:" . $v['pictUrl'];
            $tbk_info[$k]['item_url'] = $v['auctionUrl'];
            $tbk_info[$k]['reserve_price'] = $v['reservePrice'];
            $tbk_info[$k]['shop_name'] = $v['shopTitle'];
            $tbk_info[$k]['tkMktStatus'] = intval($v['tkMktStatus']);
            $tbk_info[$k]['source'] = $v['auctionUrl'];
            $tbk_info[$k]['add_time'] = time();
            $tbk_info[$k]['is_update'] = 1;
            $tbk_info[$k]['is_delete'] = 0;
            if ($v['tkRate'] >= 10 && $v['tkRate'] < 15) {
                   $rate = M('app.rate')->find(['tk_rate' => '10,15'])['fee'];
                   $tbk_info[$k]['tk_rate'] = $v['tkRate'] * $rate*$fee;
            } else if ($v['tkRate'] >= 15 && $v['tkRate'] < 20) {
                   $rate = M('app.rate')->find(['tk_rate' => '15,20'])['fee'];
                   $tbk_info[$k]['tk_rate'] = $v['tkRate'] * $rate*$fee;
            } else if ($v['tkRate'] >= 20 && $v['tkRate'] < 30) {
                   $rate = M('app.rate')->find(['tk_rate' => '20,30'])['fee'];
                   $tbk_info[$k]['tk_rate'] = $v['tkRate'] * $rate*$fee;
            } else if ($v['tkRate'] >= 30) {
                   $rate = M('app.rate')->find(['tk_rate' => '30'])['fee'];
                   $tbk_info[$k]['tk_rate'] = $v['tkRate'] * $rate*$fee;
            } else {
                   $tbk_info[$k]['tk_rate'] = $v['tkRate']*$fee;
            }
        } 
        ajaxReturn($tbk_info,'获取成功',1);  
    }
    /**
     * 产品入库
     */
    public function addGoodAct(){
        $member_id = self::getMemberIdByToken();
        $data=$_POST;
        $res = M('app.good')->addPlanGood($data);
        if($res===false){
            ajaxReturn(0,'添加失败',0);
        }else{
            ajaxReturn($res,'添加成功',1);
        }
    }
}
